<script>
import {
  copyProject,
  deleteProject,
  getAimetaProjectList
} from "@/api/aihuman/IntelligentInteraction/IntelligentInteraction";
import ReleaseDialog from "@/views/aihuman/IntelligentInteraction/addProject/ReleaseDialog.vue";
import {mapGetters} from "vuex";
import ConfigDialog from "@/views/aihuman/IntelligentInteraction/addProject/configDialog.vue";
import EmptyData from "@/components/aihuman/EmptyData/index.vue";
import {getUrl} from "@/util/aihuman/getUrl";
import ReleaseDialogTemp from "@/views/aihuman/IntelligentInteraction/addProject/ReleaseDialogTemp.vue";

export default {
  name: "IntelligentList",
  components: {ReleaseDialogTemp, EmptyData, ConfigDialog, ReleaseDialog},
  data() {
    return {
      list: [],
      searchForm: {},
      page: {
        pageNo: 1,
        pageSize: 12,
        total: 0
      },
      loading: false
    }
  },
  filters: {
    formatDate(val) {
      if (!val) {
        return ''
      }
      let date = new Date(val)
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }
  },
  created() {
    this.getList()
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        creationUse: this.vaildData(this.permission[`creation-use`], false),
        creationAdd: this.vaildData(this.permission[`creation-add`], false),
        creationDelete: this.vaildData(this.permission['creation-delete'], false),
        creationEdit: this.vaildData(this.permission['creation-edit'], false),
      }
    }
  },
  methods: {
    getUrl,
    preview(item) {
      this.$emit('on-preview', item)
    },
    editItems(item) {
      this.$emit('on-edit', item)
    },
    copyProject(item) {
      let str = item.projectName + '_副本'
      if (str.length > 30) {
        this.$message.error('复制失败：项目名称超出30个字符')
        return false
      }
      copyProject({id: item.id, projectName: item.projectName + '_副本'}).then(res => {
        this.$message.success(res.data.msg)
        this.getList()
      })
    },
    removeProject(item) {
      this.$confirm('删除项目无法找回，确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProject({id: item.id}).then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.getList()
        });
      }).catch(() => {

      });
    },
    openEdit(item) {
      let a = document.createElement('a')
      a.target = '_blank'
      a.href = `${this.getUrl()}/aihuman/aihumanEdit/aiHumanAsset/${item.id}`
      a.click()
    },
    openView(item) {
      if (item.robotInstanceId !== '') {
        let a = document.createElement('a')
        a.target = '_blank'
        a.href = `${this.getUrl()}/aihuman/aihumanShow/index.html?id=${item.id}`
        a.click()
      } else {
        let a = document.createElement('a')
        a.target = '_blank'
        a.href = `${this.getUrl()}/aihuman/aihumanEdit/aiHumanAsset/${item.id}`
        a.click()
      }
    },
    isAbsolutePath(path) {
      if (!path) return ''
      let reg = path.includes('https://')
      if (reg) {
        return path
      } else {
        return `${this.getUrl()}${path}`
      }
    },
    getList() {
      this.$nextTick(async () => {
        try {
          this.loading = true
          let params = {...this.page, projectType: 2, ...this.searchForm}
          const {data} = await getAimetaProjectList(params)
          this.page.total = data.data.total
          this.list = data.data.records
        } catch (e) {
          console.log(e)
        } finally {
          this.loading = false
        }
      })
    },
    buildConfig(item) {
      this.$refs.configDialog.open(item)
    },
    release(item) {
      // 合并发布和配置
      this.$refs.releaseDialogTemp.open(item)
      // if (item.applyType === 1) {
      //   this.buildConfig(item)
      // } else {
      //   this.$refs.releaseDialog.open(item)
      // }
    }
  }
}
</script>

<template>
  <div v-loading="loading">
    <template v-if="page.total > 0">

      <div class="project-items">
        <div class="project-box" v-for="item in list" :key="item.id">
          <div class="project-img"
               :style="{background: `url(${isAbsolutePath(item.backgroundImage)}) no-repeat center center`, backgroundSize: 'cover'}">
            <div class="project-model">
              <el-button type="primary" style="background: #318DEE; border-color: #318DEE;" @click="openView(item)">
                {{ item.robotInstanceId === '' ? '去配置' : '问答预览' }}
              </el-button>
            </div>
            <div class="project-img-tags">
              <img v-if="item.applyType === 2" src="~@/assets/aihuman/diannao.png" alt="">
              <img v-if="item.applyType === 1" src="~@/assets/aihuman/yitiji.png" alt="">
              <img v-if="item.applyType === 3" src="~@/assets/aihuman/shouji.png" alt="">
            </div>
            <img :src="getUrl() + item.previewImageUrl" alt="">
          </div>

          <div class="project-title">
            <div class="project-title__box" :title="item.projectName">
              <strong>{{ item.projectName }}</strong>
              <button v-if="permissionList.creationEdit" class="edit-ico" @click="editItems(item)">
                <img src="@/assets/aihuman/edit.png" alt="">
              </button>
            </div>

          </div>
          <div class="date-text">
            <span>{{ item.dimensionType === 3 ? 'Web3D' : item.dimensionType === 2 ? '2D' : 'UE3D' }}</span>
            <span> | </span>
            <span>{{ item.createTime | formatDate }}</span>
          </div>
          <div class="button-block">
            <button v-if="permissionList.creationUse" class="edit-btn active" @click="release(item)">发布与使用</button>
            <button v-if="permissionList.creationEdit" class="edit-btn" @click="openEdit(item)">编辑项目</button>

            <el-dropdown>
              <button class="edit-btn"><span class="el-icon-more"></span>
              </button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="preview(item)">基本信息</el-dropdown-item>
                <el-dropdown-item v-if="permissionList.creationEdit" @click.native="copyProject(item)">复制项目
                </el-dropdown-item>
                <el-dropdown-item v-if="permissionList.creationDelete" @click.native="removeProject(item)">删除项目
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>

      <div class="pagination-box">

        <el-pagination
          background
          @size-change="getList"
          @current-change="getList"
          :current-page.sync="page.pageNo"
          :page-sizes="[9, 18, 36, 72]"
          :page-size.sync="page.pageSize"
          layout="total, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>

    </template>

    <empty-data
      v-else
    />
    <release-dialog
      ref="releaseDialog"
    />

    <config-dialog
      ref="configDialog"
    />

    <release-dialog-temp
      ref="releaseDialogTemp"
    />
  </div>
</template>

<style scoped lang="scss">
@import "~@/styles/aihuman/img-list";


</style>
